package com.jxsd.edu.cn.struts2.intercept;

import org.apache.struts2.ServletActionContext;

import com.jxsd.edu.cn.tools.IPCatcher;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class IpIntercept extends  AbstractInterceptor 
{
	private static final long serialVersionUID = 1L;
	//IP查询
	private    IPCatcher  captcher=new  IPCatcher();
   //城市名称
	private    String   cityName;
	
	public   String   getCityName()
	{
	   return  cityName;	
	}
	public   void   setCityName(String  cityName)
	{
		this.cityName=cityName;
	}
	@Override
	public String intercept(ActionInvocation invocation) throws Exception 
	{
		if(ActionContext.getContext().getSession().get("cityName")!=null)
		{
			return invocation.invoke();
		}
		else
		{
			String  city=null;
			//获取IP地址
		    String  ip=ServletActionContext.getRequest().getRemoteAddr();
		   //获取IP所在城市
		    try{
	  		city=captcher.getCity(ip);
		    }catch(Exception e)
		    {
	            city=cityName;//设置为默认的城市	    	
		    }
		    if(null!=city&&!city.equals(""))
		    {
		    	cityName=city;//设置为默认城市
		    }
		    
//		    System.out.println("cityName："+cityName);
		    
		   ActionContext.getContext().getSession().put("cityName", cityName);
			return invocation.invoke();
		}
		
	}

}
